<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Sort a table by clicking its headers</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
        <style>
            .table {
                border-collapse: collapse;
            }
            .table__header {
                background-color: transparent;
                border: none;
                cursor: pointer;
            }
            .table,
            .table th,
            .table td {
                border: 1px solid #ccc;
            }
            .table th,
            .table td {
                padding: 0.5rem;
            }
            .table th {
                cursor: pointer;
                text-decoration: underline;
            }
        </style>
    </head>
    <body>
        <table id="sortMe" class="table">
            <thead>
                <tr>
                    <th data-type="number"><button class="table__header">No.</button></th>
                    <th><button class="table__header">First name</button></th>
                    <th><button class="table__header">Last name</button></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>Andrea</td>
                    <td>Ross</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>Penelope</td>
                    <td>Mills</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td>Sarah</td>
                    <td>Grant</td>
                </tr>
                <tr>
                    <td>4</td>
                    <td>Vanessa</td>
                    <td>Roberts</td>
                </tr>
                <tr>
                    <td>5</td>
                    <td>Oliver</td>
                    <td>Alsop</td>
                </tr>
                <tr>
                    <td>6</td>
                    <td>Jennifer</td>
                    <td>Forsyth</td>
                </tr>
                <tr>
                    <td>7</td>
                    <td>Michelle</td>
                    <td>King</td>
                </tr>
                <tr>
                    <td>8</td>
                    <td>Steven</td>
                    <td>Kelly</td>
                </tr>
                <tr>
                    <td>9</td>
                    <td>Julian</td>
                    <td>Ferguson</td>
                </tr>
                <tr>
                    <td>10</td>
                    <td>Chloe</td>
                    <td>Ince</td>
                </tr>
            </tbody>
        </table>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const table = document.getElementById('sortMe');
                const headers = table.querySelectorAll('th');
                const tableBody = table.querySelector('tbody');
                const rows = tableBody.querySelectorAll('tr');

                // Track sort directions
                const directions = Array.from(headers).map(function (header) {
                    return '';
                });

                // Transform the content of given cell in given column
                const transform = function (index, content) {
                    // Get the data type of column
                    const type = headers[index].getAttribute('data-type');
                    switch (type) {
                        case 'number':
                            return parseFloat(content);
                        case 'string':
                        default:
                            return content;
                    }
                };

                const sortColumn = function (index) {
                    // Get the current direction
                    const direction = directions[index] || 'asc';

                    // A factor based on the direction
                    const multiplier = direction === 'asc' ? 1 : -1;

                    const newRows = Array.from(rows);

                    newRows.sort(function (rowA, rowB) {
                        const cellA = rowA.querySelectorAll('td')[index].innerHTML;
                        const cellB = rowB.querySelectorAll('td')[index].innerHTML;

                        const a = transform(index, cellA);
                        const b = transform(index, cellB);

                        switch (true) {
                            case a > b:
                                return 1 * multiplier;
                            case a < b:
                                return -1 * multiplier;
                            case a === b:
                                return 0;
                        }
                    });

                    // Remove old rows
                    [].forEach.call(rows, function (row) {
                        tableBody.removeChild(row);
                    });

                    // Reverse the direction
                    directions[index] = direction === 'asc' ? 'desc' : 'asc';

                    // Append new row
                    newRows.forEach(function (newRow) {
                        tableBody.appendChild(newRow);
                    });
                };

                [].forEach.call(headers, function (header, index) {
                    header.addEventListener('click', function () {
                        sortColumn(index);
                    });
                });
            });
        </script>
    </body>
</html>
